package com.xm.eboot.common.config.swagger2;

import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.collect.Lists;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {

	@Bean(value = "defaultApi2")
	public Docket defaultApi2() {
		Docket docket = new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(new ApiInfoBuilder()
						.title("Eboot脚手架 RESTful APIs")
						.description("# Eboot脚手架  RESTful APIs")
						.termsOfServiceUrl("http://www.xx.com/")
						.contact(new Contact("mengxc", "http://www.xx.com/", "670403905@qq.com"))
						.version("1.0")
						.build())
//				.globalOperationParameters(getParameters()) //全局参数 暂不配置
				.groupName("2.X版本") // 分组名称
				.select()
				// 这里指定Controller扫描包路径
				.apis(RequestHandlerSelectors.basePackage("com.xm.eboot.controller"))
				.paths(PathSelectors.any())
				.build()
				.securityContexts(Lists.newArrayList(securityContext()))
				.securitySchemes(Lists.<SecurityScheme>newArrayList(apiKey()));
		return docket;
	}

	private ApiKey apiKey() {
		return new ApiKey("Authorization", "Authorization", "header");
	}

//	/**
//	 * 全局请求参数
//	 */
//	private List<Parameter> getParameters() {
//		List<Parameter> parameters = new ArrayList<>();
//		Parameter p1 = new ParameterBuilder().name("user_id").description("用户ID").modelRef(new ModelRef("string"))
//				.parameterType("header").required(true).build();
//		parameters.add(p1);
//		return parameters;
//	}

	private SecurityContext securityContext() {
		return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/.*")).build();
	}

	List<SecurityReference> defaultAuth() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		return Lists.newArrayList(new SecurityReference("Authorization", authorizationScopes));
	}
}